import pymysql
import pandas as pd
import os
import json
import pandas
import traceback
import warnings
warnings.filterwarnings("ignore")
from imp import reload
import sys
import random
import time
import datetime
import numpy as np
import itertools
from loguru import logger
import send_msg_XK
import qstock as qs
MYSQL_DB = 'yxk'
MYSQL_USER = 'yxk'
MYSQL_PASS = '..mysql_Yxk'
MYSQL_HOST_M = '58.34.1.199'
MYSQL_HOST_S = '58.34.1.199'
MYSQL_PORT = 3306
import requests


from THS.THSTrader import THSTrader
trader = THSTrader(r"C:\同花顺软件\同花顺\xiadan.exe") 

def check_pos(account) :
    if 'A' not in account:
        logger.info('not trade account')
        return
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:      
        nowdatetime=int(time.strftime('%H%M'))
        
        
        error_sql=f"select * from `yxk_realtrade_detail` where trade_status in ('error','cancel_finish') \
        and trade_time> date_sub(curdate(), interval 240 MINUTE) and account='{account}' ;"
        error_list= pd.read_sql(error_sql, con=conn)
        not_need_trade_list=[]
        not_need_trade_list.extend(list(set(error_list['stock_id'])))
        not_need_trade_list=[str(x).zfill(6) for x in not_need_trade_list]

        last_sql=f"select * from `yxk_realtrade_detail` where trade_status in ('put','start') \
        and trade_time> date_sub(curdate(), interval 10 MINUTE) and account='{account}' ;"
        last_list= pd.read_sql(last_sql, con=conn)
        last_trade_list=[]
        last_trade_list.extend(list(set(last_list['stock_id'])))
        last_trade_list=[str(x).zfill(6) for x in last_trade_list]        
        
#         pos_df= pd.read_sql(f"select * from `yxk_realtrade_pos` where  account='{account}'  \
#         and trade_date=(select date from yxk_realtrade_qry order by date desc limit 1 ) and pos>0 ;", con=conn)
        
        pos_df= pd.read_sql(f"select stock_id,sum(trade_qty) as pos ,stock_name from  yxk_realtrade_detail where  account='{account}'  \
        and ( trade_reason='finish' or trade_reason ='adjust' )  group by stock_id,stock_name having pos !=0;", con=conn)
        pos_df.set_index('stock_id',inplace=True)
    
    
        pos_df_adjust= pd.read_sql(f"select stock_id,sum(trade_qty) as pos ,stock_name from  yxk_realtrade_detail where  account='{account}'  \
        and ( trade_reason='finish' or ( trade_reason ='adjust' and trade_time<curdate() ) )  group by stock_id,stock_name having pos !=0;", con=conn)
        pos_df_adjust.set_index('stock_id',inplace=True)
        
    
        cal_pos_stock_list=list(set(pos_df.index))
        cal_pos_stock_list=[str(i).zfill(6) for i in cal_pos_stock_list]
        
        upsql0= f"delete from  yxk_realtrade_pos_qry where account='{account}'"
        cursor.execute(upsql0)
        conn.commit()
        
        pos_df.index=pos_df.index.map(lambda x:str(x).zfill(6))
        position=trader.get_position()
        print(position)
        msg='计算pos'+ ','.join(list(pos_df.index))     
        logger.info(msg)      
        if len(position)==0:
            print('空持仓')
            return
        if '证券名称' not in position[0].keys():
            logger.info('got error check_pos')
            return
        for i in range(len(position)):
            
            
            stock_name=position[i]['证券名称']
            stock_id=position[i]['证券代码']
            stock_id_str=str(stock_id).zfill(6)
            stock_pos=int(position[i]['股票余额'])
            now_price=position[i]['市价']
            now_asset=position[i]['市值']
            earn_money=position[i]['盈亏']
            avg_price=position[i]['成本价']
            frozen_pos=position[i]['冻结数量']
            avg_increace=position[i]['盈亏比例(%)']
            print(position[i])
            if stock_id_str in cal_pos_stock_list:
                cal_pos_stock_list.remove(stock_id_str)
#             if stock_id_str in not_need_trade_list:
#                 logger.info(f'not_need_trade_list {stock_id_str}')
#                 cal_pos_stock_list.remove(stock_id_str)
                
#                 continue

#             if int(stock_id) not in  list(pos_df.index) :
#                 print(stock_id,'not in pos_df')
#                 if  nowdatetime>1500 and stock_pos>0:
#                     trade_msg=f'{round(now_price*1.01,2)}|{round(now_price*0.99,2)}|0|1.03'
#                     upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
#                     `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
#                     `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`)\
#                     VALUES ('{stock_id_str}','{stock_name}','{account}', 'buy', CURRENT_TIMESTAMP, '{avg_price}', 'finish', \
#                     '{stock_pos}','adjust','{trade_msg}','CURRENT_TIMESTAMP','{avg_price}','0','adjust',\
#                     '1','0','0','{avg_price}')"
#                     print(upsql1)
#                     cursor.execute(upsql1)
#                     conn.commit()
#                 continue
                
            if stock_id_str in pos_df.index:
                cal_pos=pos_df.loc[stock_id_str,'pos']
            else:
                logger.info(f'{stock_id_str} not found')
                cal_pos=0
            if stock_id_str in pos_df_adjust.index:
                cal_pos_adjust=pos_df_adjust.loc[stock_id_str,'pos']
            else:
                cal_pos_adjust=0     
                
            upsql1=f"INSERT INTO `yxk_realtrade_pos_qry` (`account`, `updatetime`, `stock_name`, \
            `stock_id`, `pos`, `now_price`, `now_asset`, `earn_money`, `avg_price`, `frozen_pos`,  `avg_increace`,`cal_pos`) VALUES \
            ('{account}', CURRENT_TIMESTAMP,'{stock_name}', '{stock_id_str}', '{stock_pos}','{now_price}', '{now_asset}'\
            , '{earn_money}', '{avg_price}','{frozen_pos}','{avg_increace}','{cal_pos}')"
            cursor.execute(upsql1)
            conn.commit()
#             logger.info(upsql1)
            


            if stock_pos!=cal_pos and stock_id_str not in last_trade_list:    
                msg=f"{stock_id_str}-{stock_name}当前仓位:{stock_pos} 计算仓位:{cal_pos} 不一致 修改交易记录"
                logger.error(msg)
                send_msg_XK.send_msg(msg,userlist="YouXiongKai")
                if  (nowdatetime>1500 or  nowdatetime<930  ) and int(stock_pos)>0:
                 
                    deletesql=f"delete from `yxk_realtrade_detail` where account='{account}' and stock_id='{stock_id_str}' \
                    and trade_reason='adjust' and trade_time=curdate() "
                    logger.info(deletesql)
                    cursor.execute(deletesql)
                    conn.commit()

                    trade_type='sell'
#                     stock_pos_adjust=stock_pos-cal_pos_adjust
                    stock_pos_adjust=stock_pos-cal_pos_adjust
                    if stock_pos_adjust>0:
                        trade_type='buy'
                       
                    
                    
                    
                    trade_msg=f'{round(now_price*1.01,2)}|{round(now_price*0.99,2)}|0|1.03'
                    upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
                    `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
                    `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`,`trade_money`)\
                    VALUES ('{stock_id_str}','{stock_name}','{account}', '{trade_type}', CURRENT_TIMESTAMP, '{avg_price}', 'finish', \
                    '{stock_pos_adjust}','adjust','{trade_msg}','CURRENT_TIMESTAMP','{avg_price}','0','none',\
                    '1','0','0','{avg_price}','{now_price*stock_pos_adjust}')"
                    logger.info(upsql1)
                    cursor.execute(upsql1)
                    conn.commit()
#                 continuestock_pos
                 
        for stock_id_str in cal_pos_stock_list:
            
            if stock_id_str in pos_df_adjust.index:
                cal_pos_adjust=pos_df_adjust.loc[stock_id_str,'pos']
            else:
                cal_pos_adjust=0
            
            stock_name=pos_df.loc[stock_id_str,'stock_name']
            cal_pos=pos_df.loc[stock_id_str,'pos']
            avg_price=pos_df.loc[stock_id_str,'avg_price']
            msg=f"{stock_id_str}-{stock_name}当前仓位:0 计算仓位:{cal_pos} 不一致 删除历史纪录"
            logger.error(msg)
            send_msg_XK.send_msg(msg,userlist="YouXiongKai")
#             if  (nowdatetime>1500 or   nowdatetime<930 ) and int(cal_pos)>0:
            if  int(cal_pos)>0:
#                 deletesql=f"update`yxk_realtrade_detail` set trade_status='error_finish' where account='{account}' and stock_id='{stock_id_str}'"
#                 logger.info(deletesql)
#                 cursor.execute(deletesql)
#                 conn.commit()
                   
                    
                deletesql=f"delete from `yxk_realtrade_detail` where account='{account}' and stock_id='{stock_id_str}' \
                and trade_reason='adjust' "
                logger.info(deletesql)
                cursor.execute(deletesql)
                conn.commit()

                trade_type='sell'
                stock_pos_adjust=0-cal_pos_adjust
                #                     stock_pos_adjust=stock_pos
                if stock_pos_adjust>0:
                    trade_type='buy'

                if stock_pos_adjust!=0:
                    trade_msg=f'{round(avg_price*1.01,2)}|{round(avg_price*0.99,2)}|0|1.03'
                    upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
                    `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
                    `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`,`trade_money`)\
                    VALUES ('{stock_id_str}','{stock_name}','{account}', '{trade_type}', CURRENT_TIMESTAMP, '{avg_price}', 'finish', \
                    '{stock_pos_adjust}','adjust','{trade_msg}','CURRENT_TIMESTAMP','{avg_price}','0','none',\
                    '1','0','0','{avg_price}','{avg_price*stock_pos_adjust}')"
                    logger.info(upsql1)
                    cursor.execute(upsql1)
                    conn.commit()     

#                 continue          
                
                
    except Exception as e:
        traceback.print_exc()
        logger.info(e)
    finally:
        et = time.time()
        msg=f"[LOCAL]  REALTRADE Finished check_pos:, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()
      
def check_order(account):
    if 'A' not in account:
        logger.info('not trade account')
        return
    
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:       

        sql12=f"select * from yxk_realtrade_detail where account='{account}' and trade_time> date_sub(curdate(), interval 100 day)   "
        totalorder= pd.read_sql(sql12, con=conn)
        totalorder.set_index('trade_id',inplace=True)
        totalorder.index=totalorder.index.astype(object)
        sql1=f"select * from yxk_realtrade_detail where account='{account}' and trade_status in ('put','cancel_finish','error')\
        and trade_time< date_sub(now(), interval 60 MINUTE) and trade_time>=curdate() "
        unfinishorder= pd.read_sql(sql1, con=conn)
        unfinishorder.set_index('trade_id',inplace=True)
        unfinishorder.index=unfinishorder.index.astype(object)
        
        sql1=f"select * from yxk_realtrade_detail where account='{account}' and trade_status in ('put','cancel_finish','error')\
        and trade_time< date_sub(now(), interval 400 MINUTE) and trade_time>=curdate() and trade_id='0' "
        restartorder= pd.read_sql(sql1, con=conn)
        restartorder.set_index('order_id',inplace=True)
      
        
        
        
        if len(unfinishorder)==0:
            logger.info('got none unfinishorder')
            return
        
        unfinish_list=[]
        order_id_list=[]
#         logger.info(unfinishorder)
        orderlist=trader.get_today_entrusts()
        logger.info(orderlist)
        if len(orderlist)==0:
            logger.info('got none orderlist')
            return
        if '合同编号' not in orderlist[0].keys():
            logger.info('got error orderlist')
            return
            
        trade_id_list=[]
        stock_id_list=[]
        for i in range(len(orderlist)):
            status='unfinish'
            trade_price=orderlist[i]['成交均价']
            trade_id=str(orderlist[i]['合同编号'])
            trade_type= 'buy' if orderlist[i]['操作']=='买入' else 'sell'
            stock_id_str=str(orderlist[i]['证券代码']).zfill(6)
            trade_qty=orderlist[i]['成交数量']
            stock_name=orderlist[i]['证券名称']
            finish_flag=orderlist[i]['备注']
            making_price=orderlist[i]['成交均价']
            trade_id_list.append(str(trade_id))
            stock_id_list.append(str(stock_id_str))
            if str(trade_id) not in totalorder.index and finish_flag.startswith('已'):
                msg=f"{stock_id_str} 合同编号 {trade_id}不在trade_id"
                logger.info(msg)
                
                trade_msg=f'{round(trade_price*1.01,2)}|{round(trade_price*0.99,2)}|0|1.03'
                upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
                `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
                `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`,`trade_money`)\
                VALUES ('{stock_id_str}','{stock_name}','{account}', '{trade_type}', CURRENT_TIMESTAMP, '{trade_price}', 'finish', \
                '{trade_qty}','findlost','{trade_msg}','CURRENT_TIMESTAMP','{trade_price}','0','none',\
                '1','0','{trade_id}','{making_price}','{trade_qty*trade_price}')"
                logger.info(upsql1)
                cursor.execute(upsql1)
                conn.commit()
                continue
                
            elif str(trade_id) not in unfinishorder.index : 
                continue
                
            total_trade_qty=int(unfinishorder.loc[trade_id,'trade_qty'])
            if trade_qty>=np.abs(total_trade_qty) :
                msg=f"{orderlist[i]['合同编号']},{orderlist[i]['成交数量']},{orderlist[i]['成交均价']},{orderlist[i]['证券代码']} 已经完成"
                logger.info(msg)
                sql1=f"update yxk_realtrade_detail set trade_price='{trade_price}' , trade_status ='finish' , status_flow=CONCAT( status_flow,'_finish') \
                where trade_id='{trade_id}' "
                cursor.execute(sql1)
                conn.commit()
            elif unfinishorder.loc[trade_id,'trade_status']=='cancel_finish':    
                msg=f"{orderlist[i]['合同编号']},{orderlist[i]['成交数量']},{orderlist[i]['成交均价']},{orderlist[i]['证券代码']} 已经撤单完成 确认成交数量"
                logger.info(msg)
                total_trade_qty=np.abs(total_trade_qty)/total_trade_qty* trade_qty
                if trade_qty>0 :
                    sql1=f"update yxk_realtrade_detail set trade_price='{trade_price}', trade_qty ='{total_trade_qty}' , trade_status ='finish' , status_flow=CONCAT( status_flow,'_finish')   where trade_id='{trade_id}' "
                    cursor.execute(sql1)
                    conn.commit()
                else:
                    sql1=f"update yxk_realtrade_detail set  trade_qty ='0' , trade_status ='finish'  , status_flow=CONCAT( status_flow,'_finish')  \
                    where trade_id='{trade_id}' "
                    cursor.execute(sql1)
                    conn.commit()
            else:
                msg=f"{orderlist[i]['合同编号']},{orderlist[i]['成交数量']},{orderlist[i]['成交均价']},{orderlist[i]['证券代码']} 未完成待撤单"
                logger.info(msg)
                unfinish_list.append(trade_id)
                
            
            
        time.sleep(1)
        # real_trade_tool.query_order(unfinishorder)
        for order_id in restartorder.index:
            stock_id=unfinishorder.loc[trade_id,'stock_id']
            if stock_id not in stock_id_list:
                sql1=f"update yxk_realtrade_detail set   trade_status ='start', status_flow=CONCAT( status_flow,'_start')  where order_id='{order_id}'  "
                cursor.execute(sql1)
                conn.commit()
            
        for trade_id in unfinish_list and trade_id!=0: 
            msg=f'[LOCAL] cancel order {trade_id} '
            
            sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
            ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
            cursor.execute(sql)
            conn.commit()
            try:
                
                returnstatus=trader.cancel_entrust(entrust_no=str(trade_id))
                msg=f'cancel order {trade_id} '
            
                if returnstatus['success']:
                    trade_status='cancel_finish'
                    upsql1=f"update  `yxk_realtrade_detail` set trade_status='{trade_status}' , status_flow=CONCAT( status_flow,'_{trade_status}') where trade_id='{trade_id}'"
                    logger.info(upsql1)
                    cursor.execute(upsql1)
                    conn.commit()
                    
                else:
                    msg=f"cancel_fail {trade_id}"
                    send_msg_XK.send_msg(msg,userlist="YouXiongKai")
                    
            except Exception as e:
                traceback.print_exc()
                msg= f"check_order error e {e}"
                logger.error(msg)
                send_msg_XK.send_msg(msg,userlist="YouXiongKai")        
      
        
    except Exception as e:
        traceback.print_exc()
        logger.info(e)
    finally:
        et = time.time()
        msg=f"[LOCAL] REALTRADE  Finished check_order:{account}, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()
        
def put_order(account) :
   
    if 'A' not in account:
        logger.info('not trade account')
        return
    
    
    
    try:
        st = time.time()
        conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
        cursor = conn.cursor() 
        sql=f"select * from yxk_realtrade_detail where trade_time> date_sub(curdate(), interval 1 day)  and trade_status  in ('start')  and  account='{account}' order by trade_time desc"

        tradedetail= pd.read_sql(sql, con=conn)
        tradedetail['stock_id']=tradedetail['stock_id'].map(lambda x:str(x).zfill(6))   
            
        for i in range(len(tradedetail)):
            
            
        
            stock_id=tradedetail.loc[i,'stock_id']
            stock_name=tradedetail.loc[i,'stock_name']
            trade_qty=tradedetail.loc[i,'trade_qty']
            trade_price=tradedetail.loc[i,'trade_price']
            trade_flag=tradedetail.loc[i,'trade_type']
            reason=tradedetail.loc[i,'trade_reason']
            stock_id=tradedetail.loc[i,'stock_id']
            order_id=tradedetail.loc[i,'order_id']



            upsql1=f"update `yxk_realtrade_detail` set trade_status='start' , status_flow=CONCAT( status_flow,'_start') where order_id='{order_id}'"
            cursor.execute(upsql1)
            conn.commit()
            finish_status='start'
            if trade_flag=='sell':
                finish_status='put'
                returnstatus=trader.sell(stock_no=str(stock_id), amount=np.abs(trade_qty), price=trade_price) 
                trade_id=returnstatus['entrust_no']
            elif trade_flag=='buy':
                finish_status='put'
                returnstatus=trader.buy(stock_no=str(stock_id), amount=np.abs(trade_qty), price=(trade_price+0.01)) 
                trade_id=returnstatus['entrust_no']
                
            upsql1=f"update `yxk_realtrade_detail` set trade_id='{trade_id}' , trade_status='{finish_status}' , status_flow=CONCAT( status_flow,'_{finish_status}') where order_id='{order_id}'"
            cursor.execute(upsql1)
            conn.commit()

    
    except Exception as e:
        traceback.print_exc()
        msg= f"REALTRADE put_order error e {e} {stock_id}"
        logger.error(msg)
        send_msg_XK.send_msg(msg,userlist="YouXiongKai")
        logger.info(f'{account} put_order_error')
        upsql1=f"update `yxk_realtrade_detail` set trade_status='error' , status_flow=CONCAT( status_flow,'_error') where order_id='{order_id}'"
        cursor.execute(sql)
        conn.commit()
    finally:
        et = time.time()
        msg=f"[LOCAL] REALTRADE  Finished put_order:{account} time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()     
        
        
def query_cash(account):
    if 'A' not in account:
        logger.info('not trade account')
        return
    # total_assert,now_market_value,cash= real_trade_tool.query_cash()
    
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:       

        cash_dict=trader.get_balance()
        total_assert=cash_dict['总资产']
        now_market_value=cash_dict['股票市值']
        cash=cash_dict['可用金额']
        logger.info(cash_dict)       
    
        upsql1=f"update `yxk_realtrade_qry` set cash='{cash}', market_value='{now_market_value}',  total_assert='{total_assert}' \
         where updatetime >= NOW() - INTERVAL 10 MINUTE and account='{account}'; "
        # logger.info(upsql1)
        cursor.execute(upsql1)
        conn.commit()

 
    except Exception as e:
        traceback.print_exc()
        logger.info(e)
    finally:
        et = time.time()
        msg=f"[LOCAL]  REALTRADE  Finished query_cash:{account}, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()
        
def trade_account():
    LOG_FPATH = 'trade.log'
    logger.add(LOG_FPATH)
    account='A50549'
    while True:
        dayofday=datetime.datetime.now().isoweekday()
        weekday=int(dayofday)
        nowdatetime=int(time.strftime('%H%M'))
        logger.info("++"*20)
        timestr=f"week:{weekday} nowdatetime:{nowdatetime}"
        logger.info(timestr)
        if weekday>5:
            logger.info('周末不交易')
            break
        if nowdatetime>=1505:
            query_cash(account)
            check_order(account)
            check_pos(account)
            put_order(account) 
            logger.info('超过1505 程序结束')
            break
        elif nowdatetime<932 or (nowdatetime>1129 and nowdatetime<1300) or nowdatetime>1453:
            logger.info('不是交易时间') 
            time.sleep(60)
            continue
       
        try:
            if nowdatetime%2==0:
                check_order(account)
            if nowdatetime%8==0:
                check_pos(account)
            query_cash(account)
            put_order(account) 
            time.sleep(60)
        except Exception as e:
            msg= f"REALTRADE  real_trade error e {e}"
            logger.error(e)
            send_msg_XK.send_msg(msg,userlist="YouXiongKai") 
            
if __name__ == '__main__': 
    


    trade_account()
   